package cn.exrick.xboot.common.qywxCode;

import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.utils.ResponseUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.base.dao.mapper.UserRoleMapper;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信
 */

@RestController
@RequestMapping("/xboot/user")
@CacheConfig(cacheNames = "user")
@EnableTransactionManagement
@Component
public class SendQywxCodeController {

    static Log log = LogFactory.get(SendQywxCodeController.class);
    //企业微信token
    public String wxtoken;
    //发送文本josn
    public String postdata;
    //返回状态
    public String resp;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserService userService;
    @Autowired
    UserRoleMapper userRoleMapper;

    //向用户的企业微信发送验证码
    @RequestMapping(value = "/sendcode", method = RequestMethod.POST)
    public void getQywxCode(@RequestParam("username") String username, HttpSession session, HttpServletResponse response) {
        IsWxUser isWxUser = new IsWxUser();

        WeChatMsgSend weChatMsgSend = new WeChatMsgSend();
        WeChatUrlData weChatUrlData = new WeChatUrlData();

        //生成随机数
        CreateRandomNums nums = new CreateRandomNums();
        String wxcode = nums.createRandomNum(6);

        //获取系统当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(System.currentTimeMillis());
        int isWx=isWxUser.isWx(username);
        try {
            if (isWx==3){
                //获取企业微信token
                wxtoken = weChatMsgSend.getToken("wwd3f7961b41c99135",
                        "w_ulMFEB9xakLJu1p59y-qz1w7hr_i2lwqTUYVcJRiM");
                //根据企业微信用户名，下发验证码
                IsPhoneNum is = new IsPhoneNum();
                if (is.isMobile(username)) {
                    String mobileUsername = userRoleMapper.findMobileByName(username);
                    postdata = weChatMsgSend.createpostdata(mobileUsername,
                            "text",
                            1000002,
                            "content",
                            "您的potal登录验证码为:" + wxcode +
                                    "\n\r" +
                                    "发送时间" + dateStr +
                                    "\n\r" +
                                    "验证码有限时间为60秒，过期请重新发送");
                } else {
                    postdata = weChatMsgSend.createpostdata(username,
                            "text",
                            1000002,
                            "content",
                            "您的potal登录验证码为:" + wxcode +
                                    "\n\r" +
                                    "发送时间" + dateStr +
                                    "\n\r" +
                                    "验证码有限时间为60秒，过期请重新发送");
                }
                resp = weChatMsgSend.post("utf-8",
                        weChatMsgSend.CONTENT_TYPE,
                        weChatUrlData.getSendMessage_Url(),
                        postdata,
                        wxtoken);
                session.setAttribute("wxcode", wxcode);
                //将用户名，验证码，下发验证码时间存入redis中,设置
                RedisSerializer stringSerializer = new StringRedisSerializer();
                redisTemplate.setKeySerializer(stringSerializer);
                redisTemplate.setValueSerializer(stringSerializer);

                redisTemplate.opsForValue().set(SecurityConstant.USER_QYWX + wxcode, wxcode, 60, TimeUnit.SECONDS);

            } else if (isWx==2){
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "微信登录权限被禁用，开通请联系管理员"));
            }else{
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 403, "输入的用户名有误。请重新输输入"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

